<template>
  <PageWrapper v-loading="loadingRef" contentFullHeight fixedHeight contentClass="flex">
    <AppTree class="w-1/4 xl:w-1/5 mr-2" @select="handleSelect" />

    <PageWrapper contentFullHeight fixedHeight dense class="w-3/4 xl:w-4/5 overflow-hidden">
      <AdVxeTable
        @register="registerTable"
        @checkbox-change="
          () => {
            hasRowSelected = getSelectedRows()?.length > 0;
          }
        "
        @fetch-success="clearSelectedRows"
        @fetch-error="clearSelectedRows"
      >
        <template #tools>
          <Authority :value="'Root.Mobile.Admin.AppVersion.Create'">
            <a-button type="primary" @click="handleCreate">
              <Icon icon="ant-design:plus-circle-outlined" />{{ t('common.addText') }}
            </a-button>
          </Authority>
          <Authority :value="'Root.Mobile.Admin.AppVersion.Delete'">
            <a-button
              type="primary"
              color="error"
              :disabled="!hasRowSelected"
              @click="handleDeleteBatch"
            >
              <Icon icon="ant-design:delete-outlined" />{{ t('common.delText') }}
            </a-button>
          </Authority>
        </template>

        <template #actionCol="{ row }">
          <TableAction
            outside
            :actions="[
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                tooltip: t('common.delText'),
                auth: 'Root.Mobile.Admin.AppVersion.Delete', // 权限控制
                // ifShow: (_action) => {
                //   return row?.IsSystem !== true; // 根据业务控制是否显示: 是否可删除的数据权限状态
                // },
                popConfirm: {
                  title: t('common.delConfirmText'),
                  placement: 'left',
                  confirm: handleDelete.bind(null, row),
                },
              },
            ]"
            :dropDownActions="[
              {
                icon: 'clarity:details-line',
                label: t('common.detailText'),
                auth: 'Root.Mobile.Admin.AppVersion.Get', // 权限控制
                onClick: handleDetail.bind(null, row),
              },
              {
                icon: 'clarity:note-edit-line',
                label: t('common.editText'),
                auth: 'Root.Mobile.Admin.AppVersion.Update', // 权限控制
                onClick: handleEdit.bind(null, row),
              },
            ]"
          />
        </template>
      </AdVxeTable>
    </PageWrapper>

    <DetailModal @register="registerDetailFormModal" :afterSubmitFunc="handleAfterDetailSubmit" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, h } from 'vue';
  import { useI18n } from '@/hooks/web/useI18n';
  import { Authority } from '@/components/Authority';
  import { PageWrapper } from '@/components/Page';
  import { AdVxeTable, useAdVxeTable, TableAction } from '@/components/AdVxeTable';
  import { useMessage } from '@/hooks/web/useMessage';
  import Icon from '@/components/Icon/Icon.vue';

  import { FilterGroup, FilterRule, AjaxResult } from '#/request';
  import { FilterOperateEnum } from '@/enums/filterOperateEnum';

  import {
    // readAppVersion,
    readAppVersionSimple,
    // createAppVersion,
    deleteAppVersion,
  } from '@/api/mobile/admin/appversion';

  import { useModal } from '@/components/AdVxeModal';
  import { FormModeEnum } from '@/enums/formEnum';

  import AppTree from '@/views/mobile/app/tree.vue';

  import { columns } from './index.data';
  import DetailModal from './detail.vue';

  defineOptions({ name: 'MobAppVersionPage' });

  const { t } = useI18n();
  const { createConfirm, createMessage } = useMessage();

  const loadingRef = ref(false);
  function openWrapLoading() {
    loadingRef.value = true;
  }
  function closeWrapLoading() {
    loadingRef.value = false;
  }

  const hasRowSelected = ref(false);
  const appRef = ref<any>(null);

  const [registerTable, { getTable, reload, setProps }] = useAdVxeTable({
    id: 'ea_mobild_appversion_page',
    // 表标题呈现器
    title: t('mobile.route.appVersion.listText'),
    // 表格数据接口请求对象
    api: readAppVersionSimple,
    // 详情表单
    detailForm: {
      // 表单标识
      formIndex: 'ea_mobild_appversion_detail',
      // 主键字段
      keyField: 'Id',
      // 详情表单抬头
      title: t('mobile.route.appVersion.title'),
    },
    // 表单列信息 AdColumn[]
    columns,
    // 使用搜索表单
    searchForm: true,
    //行选择设置
    selection: 'checkbox',
    // 是否带有边框 boolean | default（默认）, full（完整边框）, outer（外边框）, inner（内边框）, none（无边框）
    border: false,
    // 是否显示序号列
    showSeqColumn: true,
    // 表格右侧操作列配置 AdColumn
    actionColumn: {
      width: 80,
      title: t('common.actionText'),
      fixed: 'right',
      slots: { default: 'actionCol' },
    },
  });

  function getSelectedRows() {
    const $table = getTable();
    if ($table) {
      const rows = $table.getCheckboxRecords();
      return rows;
    }
    return [];
  }
  function clearSelectedRows() {
    const $table = getTable();
    if ($table) {
      $table.clearCheckboxRow();
    }
  }

  /** 处理仓库选择 */
  async function handleSelect(key: any, e: any, data: any) {
    // console.log('handleSelect', { key, e });
    let searchInfo: FilterGroup | undefined = undefined;
    if (!e.node.group) {
      if (key) {
        appRef.value = {
          Id: key,
          Code: data.Code,
          Platform: data.Platform,
          Name: data.Name,
          Author: data.Author,
          Email: data.Email,
          PhoneNumber: data.PhoneNumber,
        };
        searchInfo = new FilterGroup();
        searchInfo.Rules.push(new FilterRule('AppId', key, FilterOperateEnum.Equal));
      } else {
        appRef.value = null;
        searchInfo = undefined;
      }
    } else {
      appRef.value = null;
      searchInfo = undefined;
    }
    setProps({ searchInfo: searchInfo });
    // console.log('handleSelect-searchInfo', searchInfo.value);
    reload();
  }

  const [registerDetailFormModal, detailModalMethods] = useModal();
  /** 处理新增 */
  async function handleCreate() {
    const appId = appRef.value?.Id;
    const appCode = appRef.value?.Code;
    const appPlatform = appRef.value?.Platform;
    const appName = appRef.value?.Name;
    const appAuthor = appRef.value?.Author;
    const appEmail = appRef.value?.Email;
    const appPhoneNumber = appRef.value?.PhoneNumber;
    detailModalMethods.openModal(true, {
      formMode: FormModeEnum.Add,
      record: {
        AppId: appId,
        AppCode: appCode,
        AppPlatform: appPlatform,
        AppName: appName,
        Author: appAuthor,
        Email: appEmail,
        PhoneNumber: appPhoneNumber,
      },
    });
  }
  /** 处理查看详情 */
  async function handleDetail(record: any) {
    if (record && record.Id) {
      openWrapLoading();
      try {
        //TODO:详情表单的弹窗
        detailModalMethods.openModal(true, {
          formMode: FormModeEnum.ReadOnly,
          record: record,
        });
      } finally {
        closeWrapLoading();
      }
    }
  }
  /** 处理编辑 */
  async function handleEdit(record: any) {
    if (record && record.Id) {
      openWrapLoading();
      try {
        //TODO:详情表单的弹窗
        detailModalMethods.openModal(true, {
          formMode: FormModeEnum.Edit,
          record: record,
        });
      } finally {
        closeWrapLoading();
      }
    }
  }
  /** 处理删除 */
  async function handleDelete(record: any) {
    const result = await deleteAppVersion([record.Id]);
    if (result.Succeeded) {
      createMessage.success(t('common.successText'));
      await reload();
    }
  }
  /** 处理批量删除 */
  async function handleDeleteBatch() {
    const selectedRows = getSelectedRows();
    if (selectedRows?.length > 0) {
      createConfirm({
        zIndex: 999999999,
        iconType: 'warning',
        title: () => h('span', t('sys.app.logoutTip')),
        content: () => h('span', t('common.delConfirmText')),
        onOk: async () => {
          try {
            openWrapLoading();
            const recordIds = selectedRows.map((item) => {
              return item.Id;
            });
            const result = await deleteAppVersion(recordIds);
            if (result.Succeeded) {
              createMessage.success(t('common.successText'));
              await reload();
              clearSelectedRows();
            }
          } finally {
            closeWrapLoading();
          }
        },
      });
    }
  }

  /** 处理详情表单提交后回调，返回true关闭窗体 */
  async function handleAfterDetailSubmit(
    formMode: FormModeEnum,
    result?: AjaxResult | null,
    _record?: any,
  ) {
    if (result) {
      if (result?.Succeeded) {
        if (result?.Content) {
          createMessage.success(result.Content);
        } else {
          createMessage.success(t('common.successText'));
        }
        switch (formMode) {
          case FormModeEnum.Add:
          case FormModeEnum.Edit:
          case FormModeEnum.Delete:
            await reload();
            break;
        }
        return true;
      } else {
        return false;
      }
    }
    return true;
  }
</script>
